package com.dv.schoolshop.util;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;
import com.dv.schoolshop.entity.ResultBean;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.io.BufferedReader;
import java.io.InputStreamReader;

//import com.google.gson.Gson;
//import com.google.gson.annotations.SerializedName;

//需要在pom.xml引入以下依赖
/**
 <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
**/
public class ShortNetAddressUtil {
static String appid = "wxee5f3b3774b28ede";
static String appsrcret = "1806891e9a0fd6c10c1eb86d4e15d935";

public static void main(String[] args) {
    String longUrl = "https://baidu.com";
    System.out.println(getShortURL(longUrl));

}

/**
 * 微信根据APPID和APPSECRET获取token
 * 
 * @param appid
 * @param appsrcret
 * @return 返回转换后的短链接
 */
public static String getToken(String appid, String appsrcret) throws Exception {
    // 访问地址
    String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    String APPID = appid;
    String APPSECRET = appsrcret;
    String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
    JSONObject jsonObject = HttpUtils.httpsUtil(request_url, "GET", null);
    if (null != jsonObject) {
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }
    return null;
}

/**
 * 将长链接转为短链接(调用的微信短网址API) 需要token
 * 
 * @param longUrl   需要转换的长链接url
 * @param appid
 * @param appsrcret
 * @return 返回转换后的短链接
 */
public static String getShortURL(String longUrl) {
	ResultBean<String> result = new ResultBean<>();
    String token;
    try {
        token = getToken(appid, appsrcret);
        String uri = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
        String url = uri.replace("ACCESS_TOKEN", token);
        String param = "{\"action\":\"long2short\"," + "\"long_url\":\"" + longUrl + "\"}";
        // 调用接口创建菜单
        JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", param);
        System.out.println(jsonObject);
        if (null != jsonObject) {
            result.setCode(jsonObject.getInteger("errcode"));
            result.setData(jsonObject.getString("short_url"));
            return result.getData();
        } else {
            return null;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
}
